package cn.ailanyin.home.module.file.utils;

import cn.ailanyin.home.common.exception.ServiceException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * FileUtil
 *
 * @author ailanyin
 * @date 2024-04-19 17:17:18
 */
public class FileUtil extends cn.hutool.core.io.FileUtil {

    public static String upload(MultipartFile file, String uploadPath) {
        if (Objects.isNull(file) || file.getSize() == 0 || StrUtil.isBlank(file.getOriginalFilename())) {
            return null;
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String path = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + java.util.UUID.randomUUID().toString() + "." + getExtension(filename);
            File absoluteFile = getAbsoluteFile(uploadPath, path);
            // 写入流
            cn.hutool.core.io.FileUtil.writeFromStream(inputStream, absoluteFile, false);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件失败");
        } finally {
            IoUtil.close(inputStream);
        }
    }

    /**
     * 创建文件
     *
     * @param fileName 文件名
     * @return file
     */
    private static File getAbsoluteFile(String uploadPath, String fileName) {
        File desc = new File(uploadPath + "/" + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                boolean result = desc.getParentFile().mkdirs();
                if (!result) {
                    throw new ServiceException("上传文件-创建父目录失败");
                }
            }
        }
        return desc;
    }

    /**
     * 获取文件的后缀
     *
     * @param filename 文件名
     * @return 后缀名
     */
    public static String getExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }
}
